#!/bin/bash
set -euxo pipefail

# if darwin, add PATH="/usr/local/opt/bison/bin:$PATH"
if [[ $OSTYPE == "darwin"* ]]; then
  export PATH="/opt/homebrew/opt/bison/bin:$PATH"
fi
bison --version

TAG=$(git describe --tags --exact-match HEAD)
RELEASE_DIR=${RELEASE_DIR:-"tmp/releases/${TAG}-$(uname -s)/"}

cargo test --release
rm -rf "${RELEASE_DIR}"

mkdir -p "${RELEASE_DIR}"

cargo build
cargo build --release

release_tarball_os="$(uname -s)"
release_tarball_arch="$(uname -m)"
cargo_target_dir_prefix=""

cargo_dir="target/${cargo_target_dir_prefix}"
cp "${cargo_dir}release/rubyfmt-main" "${RELEASE_DIR}/rubyfmt"
pwd
cp "${cargo_dir}debug/rubyfmt-main" "${RELEASE_DIR}/rubyfmt-debug"
pwd
cp RELEASE_README.md "${RELEASE_DIR}/RELEASE_README"

# check the binary
RES=$(echo 'a(1)' | "${RELEASE_DIR}/rubyfmt")
if [ "$RES" != "a(1)" ]; then
  echo "formatting failed"
  exit 1
fi

tar -cvz -f "rubyfmt-${TAG}-${release_tarball_os}-${release_tarball_arch}.tar.gz" "${RELEASE_DIR}"
